import React, { useState, createContext } from "react";
const PersonContext = createContext();
const ChildContext = createContext();
function App() {
  const [person, setPerson] = useState({
    name: "Mike",
    age: 26,
    child: {
      name: "cili",
      age: 1,
    },
  });

  const handleClick = () => {
    setPerson({
      ...person,
      age: person.age + 1,
    });
  };
  const addChild = () => {
    setPerson({
      ...person,
      child: {
        ...person.child,
        age: person.child.age + 1,
      },
    });
  };
  return (
    <div className="App">
      <PersonContext.Provider value={person}>
        <button onClick={handleClick}>点我试试看</button>
        <ChildContext.Provider value={{ a: person.child, b: addChild }}>
          <ShowChild />
        </ChildContext.Provider>
        <ShowPerson />
      </PersonContext.Provider>
    </div>
  );
}

function ShowPerson() {
  return (
    <PersonContext.Consumer>
      {(person) => (
        <div>
          {person.name} {person.age}
        </div>
      )}
    </PersonContext.Consumer>
  );
}
function ShowChild() {
  return (
    <ChildContext.Consumer>
      {(value) => (
        <div onClick={value.b}>
          {value.a.name}
          {value.a.age}
        </div>
      )}
    </ChildContext.Consumer>
  );
}
export default App;
